package com.study.ming.studydemo.thd;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierDemo2 {
    public static void main(String[] args) {
        /**
         * 创建一个新的 CyclicBarrier ，当给定数量的线程（线程）等待时，它将跳闸， 当屏障跳闸时执行给定的屏障动作，由最后一个进入屏障的线程执行。
         */
        CyclicBarrier cbRef = new CyclicBarrier(5, new Runnable() {
            public void run() {
                System.out.println("都到了");
            }
        });

        Thread_01[] threads = new Thread_01[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread_01(cbRef);
            threads[i].start();
        }

    }
}

class Thread_01 extends Thread {

    private CyclicBarrier cbRef;

    public Thread_01(CyclicBarrier cbRef) {
        super();
        this.cbRef = cbRef;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + "ready!!!");
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5, 10));
            System.out.println(Thread.currentThread().getName() + "到了!" + System.currentTimeMillis());
            // 等待所有 parties已经在这个障碍上调用了 await 。
            cbRef.await();
            System.out.println("开始嗨...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}